package com.umeox.watch.moto.dataservice.mqtt;

import android.os.Build;
import android.text.TextUtils;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.mqtt.CryptoUtil;
import com.umeox.watch.moto.dataservice.BuildConfig;
import com.umeox.watch.moto.dataservice.base.BaseApp;
import com.umeox.watch.moto.dataservice.constants.InternalConstant;


public class ConnectConfig {
    public String channelHost;
    public String userName;
    public String clientId;
    public String password;
    public int keepAliveIntervalSec;

    public ConnectConfig(String deviceId) {
        //mqttClientId: clientId&verb=0,method=hmacmd5,ts=123
        //mqttUserName: productKey&deviceName
        //mqttPassword: sign_hmac(productSecret,stringForSignature)
        channelHost = BuildConfig.BROKER_HOST;
        String deviceSecret = BaseApp.getInstance().getMmkv().decodeString(InternalConstant.KEY_DEVICE_SECRET);
        Logger.i("deviceSecret=" + deviceSecret);
        String stringForSignature;
        if (TextUtils.isEmpty(deviceSecret)) {
            clientId = deviceId + "&verb=0,method=hmacmd5,ts=" + System.currentTimeMillis();
            stringForSignature = "deviceName" + deviceId + "productKey" + BuildConfig.PRODUCT_KEY + "ts" + System.currentTimeMillis();
            deviceSecret = BuildConfig.PRODUCT_SECRET;
        } else {
            clientId = deviceId + "&verb=1,method=hmacmd5,ts=" + System.currentTimeMillis() + ",fv=" + Build.DISPLAY;
            stringForSignature = "clientId" + deviceId + "deviceName" + deviceId + "productKey" + BuildConfig.PRODUCT_KEY + "ts" + System.currentTimeMillis();
        }
        userName = BuildConfig.PRODUCT_KEY + "&" + deviceId;
        try {
            password = CryptoUtil.hmacMd5(stringForSignature, deviceSecret);
            Logger.i("password=" + password);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.i("hmacMd5 加密报错");
        }
        keepAliveIntervalSec = BuildConfig.KEEP_ALIVE_SECONDS;
    }

    public boolean checkValid() {
        return !TextUtils.isEmpty(this.channelHost)
                && !TextUtils.isEmpty(this.clientId);
    }

    @Override
    public String toString() {
        return "ConnectConfig{" +
                "channelHost='" + channelHost + '\'' +
                ", userName='" + userName + '\'' +
                ", clientId='" + clientId + '\'' +
                ", password='" + password + '\'' +
                ", keepAliveIntervalSec=" + keepAliveIntervalSec +
                '}';
    }
}
